//
//  MYHomeViewController.m
//  奇闻
//
//  Created by 似水灵修 on 14-11-20.
//  Copyright (c) 2014年 MingYueGuCheng. All rights reserved.
//

#import "MYHomeViewController.h"
#import "MYTitleButton.h"
#import "MYPopMenu.h"
#import "MYNavigationController.h"
#import "MYAccountTool.h"
#import "MYStatus.h"
#import "UIImageView+WebCache.h"
#import "MYUser.h"
#import "MJRefresh.h"
#import "MYHttpTool.h"
#import "MYStatusTool.h"
#import "MYUserTool.h"
#import "MYStatusCellTableViewCell.h"
#import "MYStatusCellTableViewCellFrame.h"
#import "MYMenuViewController.h"


@interface MYHomeViewController ()
@property (nonatomic, strong) NSMutableArray *statusesFrame;
@property (nonatomic, weak) UIButton *titleButton;
//菜单控制器
@property (nonatomic, strong) UIViewController *popVC;
@property (nonatomic, assign, getter=isRefreshing) BOOL refreshing;//记录刷新状态
@property (nonatomic, strong) MYMenuViewController *menuViewController;
@end

@implementation MYHomeViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // 设置首页导航条的内容
    [self setupNavBar];
    //添加上下拉刷新控制
    [self setupRefresh];
    // 取消分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.view.backgroundColor = MYRGBColor(201, 201, 201, 1);
    
}
//添加上下拉刷新控制
- (void)setupRefresh
{
    // 添加下拉刷新控件
    // 当你下拉的时候就会调用Target对象action方法
    [self.tableView addHeaderWithTarget:self action:@selector(loadNewStatuses)];
    // 手动下拉刷新
    [self.tableView headerBeginRefreshing];
    // 添加上拉刷新控件
    // 当你上拉的时候就会调用Target对象action方法
    [self.tableView addFooterWithTarget:self action:@selector(loadMoreStatuses)];
}
- (void)refresh
{
    [self.tableView headerBeginRefreshing];
}
//获取最新的奇闻数据(下拉、获取新数据)
- (void)loadNewStatuses
{
    /**
     *  access_token	false	string	采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得。
     since_id	false	int64	若指定此参数，则返回ID比since_id大的奇闻（即比since_id时间晚的奇闻），默认为0。
     GET请求
     */
    // 下啦刷新 通知tabBar清空记录总共的未读数
    /**
     *  NotificationName:通知的名称
     object:谁发出的通知
     */
    if (self.isRefreshing) {//正在刷新
        return;
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:MYBeginNewNote object:nil];
    self.refreshing = YES;
    id sinceID = nil;
    if (self.statusesFrame.count) {
        MYStatusCellTableViewCellFrame *statusF = [self.statusesFrame firstObject];
        sinceID = statusF.status.idstr;
    }
    [MYStatusTool newStatusWithSinceID:sinceID success:^(NSArray *statuses) {
        self.refreshing = NO;
        // 提示最新奇闻数
        [self showNewStatusesCount:statuses.count];
        [self.tableView headerEndRefreshing];//停止头部刷新
        NSMutableArray *arrM = [NSMutableArray array];
        for (MYStatus *s in statuses) {
            MYStatusCellTableViewCellFrame *SF = [[MYStatusCellTableViewCellFrame alloc] init];
            SF.status = s;
            [arrM addObject:SF];
        }
        NSRange range = NSMakeRange(0, statuses.count);
        // location : 插入哪个角标
        // len :插入奇闻数组的个数
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        [self.statusesFrame insertObjects:arrM atIndexes:indexSet];
        // 获取到新数据的时候,刷新表格
        [self.tableView reloadData];

    } failure:^(NSError *error) {
 //       MYLog(@"%@", error);
    }];
}
// 获取最多的奇闻数据(上拉、获取旧数据)
- (void)loadMoreStatuses
{
    /**
     *  access_token	false	string	采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得。
     max_id	false	int64	若指定此参数，则返回ID小于或等于max_id的奇闻，默认为0。
     GET请求
     */
    // 上啦刷新 通知tabBar记录总共的未读数
    /**
     *  NotificationName:通知的名称
     object:谁发出的通知
     */
    if (self.isRefreshing) {
        return;
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:MYBeginMoreNote object:nil];
    self.refreshing = YES;
    id maxID = nil;
    if (self.statusesFrame.count) {
        MYStatusCellTableViewCellFrame *status = [self.statusesFrame lastObject];
        maxID = @([status.status.idstr longLongValue] - 1);
    }
    [MYStatusTool moreStatusWithMaxID:maxID success:^(NSArray *statuses) {
        self.refreshing = NO;
        [self.tableView footerEndRefreshing];//停止尾部刷新
        NSMutableArray *arrM = [NSMutableArray array];
        for (MYStatus *s in statuses) {
            MYStatusCellTableViewCellFrame *SF = [[MYStatusCellTableViewCellFrame alloc] init];
            SF.status = s;
            [arrM addObject:SF];
        }

        [self.statusesFrame addObjectsFromArray:arrM];
        // 获取到新数据的时候,刷新表格
        [self.tableView reloadData];
    } failure:^(NSError *error) {
     //   MYLog(@"%@", error);
    }];
}
- (UIViewController *)popVC
{
    if (nil == _popVC) {
        _popVC = [[UIViewController alloc] init];
    }
    return _popVC;
}

- (void)setupNavBar
{
    // 创建左边item
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithNormalImageName:@"navigationbar_friendsearch" highImageName:@"navigationbar_friendsearch_highlighted" target:self action:@selector(friendsearch)];
    // 创建右边item
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithNormalImageName:@"navigationbar_pop" highImageName:@"navigationbar_pop_highlighted" target:self action:@selector(pop)];
    // titleView
    MYTitleButton *titleBtn = [[MYTitleButton alloc] init];
    //获取用户信息
    NSString *name = [MYAccountTool account].name;
    // 都需要请求用户,防止以后用户把名称改了
    [MYUserTool userInfoDidSuccess:^(MYUser *user) {
        [self.titleButton setTitle:user.name forState:UIControlStateNormal];
    } failure:^(NSError *error) {
//        MYLog(@"%@", error);
    }];
  
    [titleBtn setNormalTitle:name?name:@"首页"];
    [titleBtn addTarget:self action:@selector(titleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = titleBtn;
}
- (void)friendsearch
{
    
}
- (void)pop
{
    
}
// 提示最新奇闻数
- (void)showNewStatusesCount:(NSInteger)count
{
    if (0 == count) {
        return;
    }
    CGFloat labelH = 35;
    CGFloat labelW = self.view.width;
    CGFloat labelY = CGRectGetMaxY(self.navigationController.navigationBar.frame) - labelH;
    CGFloat labelX = 0;
    // 弹出最新奇闻数控件
    UILabel *statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(labelX, labelY, labelW, labelH)];
//    statusLabel.backgroundColor = MYRandomColor;
    statusLabel.text = [NSString stringWithFormat:@"%zi 个奇闻信息", count];
    statusLabel.textAlignment = NSTextAlignmentCenter;
    statusLabel.textColor = MYRGBColor(39.0, 85.0, 12.0, 1.0);
    [self.navigationController.view insertSubview:statusLabel belowSubview:self.navigationController.navigationBar];
    [UIView animateWithDuration:0.25 animations:^{
        statusLabel.transform = CGAffineTransformMakeTranslation(0, labelH);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:1.0 animations:^{
            statusLabel.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [statusLabel removeFromSuperview];
        }];
    }];
    
}
#pragma mark - 导航栏标题按钮点击事件
- (void)titleBtnClick:(MYTitleButton *)btn
{
    btn.selected = !btn.selected;
    MYMenuViewController *menuViewController = [[MYMenuViewController alloc] init];
    self.menuViewController = menuViewController;
    MYPopMenu *menu = [MYPopMenu popMenuWithContentView:menuViewController.view];
    if (btn.selected) {
        MYCover *cover = [MYCover show];
        cover.dimBackground = YES;
        
        CGFloat menuW = 200;
        CGFloat menuH = 150;
        CGFloat menuX = (MYScreenBounds.size.width - menuW) * 0.5;
        CGFloat menuY = CGRectGetMaxY(self.navigationController.navigationBar.frame) - 10;
        CGRect rect = CGRectMake(menuX, menuY, menuW, menuH);
        
        __weak typeof (self) weakSelf = self;
        cover.operateBlock = ^{
            [menu dismiss];
            weakSelf.menuViewController = nil;
            btn.selected = !btn.selected;
        };
        [menu showInRect:rect];
    }
    else
    {
        [menu dismiss];
    }
}
- (NSMutableArray *)statusesFrame
{
    if (nil == _statusesFrame) {
        _statusesFrame = [NSMutableArray array];
    }
    return _statusesFrame;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.statusesFrame.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MYStatusCellTableViewCell *cell = [MYStatusCellTableViewCell statusCellTableView:tableView];
    cell.statusF = self.statusesFrame[indexPath.row];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self.statusesFrame[indexPath.row] cellH];
}
@end
